﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Chisel.Core
{
	public partial class DiagramViewer : UserControl
	{
		public DiagramViewer()
		{
			InitializeComponent();

			Loaded += new RoutedEventHandler(OnLoaded);

			SizeChanged += new SizeChangedEventHandler(OnSizeChanged);
		}

		void OnLoaded(object sender, RoutedEventArgs e)
		{
			CanvasSize = new Point(_canvas.ActualWidth, _canvas.ActualHeight);
			ZoomControl.ValueChanged += OnZoomChanged;

		}

		private void OnSizeChanged(object sender, SizeChangedEventArgs e)
		{
			_scrollViewer.Width = e.NewSize.Width;
			_scrollViewer.Height = e.NewSize.Height;
		}

		/// <summary>
		/// The canvas in the viewer.
		/// </summary>
		public DiagramCanvas Canvas
		{
			get { return _canvas; }
		}

		#region Actors

		/// <summary>
		/// Adds an actor to the diagram.
		/// </summary>
		public void AddActor(Actor actor)
		{
			_canvas.Actors.Add(actor);
			_canvas.Children.Add(actor);
		}

		#endregion


		#region The Canvas

		/// <summary>
		/// The size of the canvas.
		/// </summary>
		public Point CanvasSize
		{
			get { return new Point(_canvas.Width, _canvas.Height); }
			set
			{
				_canvas.Width = value.X;
				_canvas.Height = value.Y;
			}
		}

		#endregion

		#region Zooming

		/// <summary>
		/// The zoom control for this canvas.
		/// </summary>
		public ZoomControl ZoomControl
		{
			get { return _zoomControl; }
		}

		/// <summary>
		/// Handles an external zoom changed event.
		/// </summary>
		public void OnZoomChanged(object sender, ZoomEventArgs args)
		{
			ScaleTransform scale;
			if (args.Value > 1)
			{
				scale = new ScaleTransform() {
					ScaleX = args.Value,
					ScaleY = args.Value, 
					CenterX = _canvas.Width / 2,
					CenterY = _canvas.Height / 2
				};
			}
			else
			{
				scale = new ScaleTransform() {
					ScaleX = args.Value,
					ScaleY = args.Value
				};
			}
			_canvas.RenderTransform = scale;
			_canvasBorder.Width = _canvas.Width * _zoomControl.Value;
			_canvasBorder.Height = _canvas.Height * _zoomControl.Value;
			//_canvasBorder.Padding = new Thickness(_scrollViewer.HorizontalOffset, _scrollViewer.VerticalOffset, 0, 0);
			//_scrollViewer.InvalidateScrollInfo();
			//_scrollViewer.InvalidateMeasure();
		}

		#endregion
	}
}
